package cn.jilian.meta.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jilian.common.util.MapUtil;
import cn.jilian.dao.AttrDAO;
import cn.jilian.entity.Attr;
import cn.jilian.entity.MField;
import cn.jilian.entity.Meta;
import cn.jilian.meta.service.DataService;
import cn.jilian.meta.service.MetaService;

@Service
public class DataServiceImpl implements DataService {

	@Autowired
	private MetaService metaService;
	@Autowired
	private AttrDAO attrDAO;
	
	@Override
	public int saveAttrs(long id, Map<String, String> attrs, long metaId) {
		Meta meta=metaService.getMetaById(metaId);
		Integer storeRankId=Integer.parseInt(meta.getAttr(Meta.STORE_RANK,"210401"));
//		Meta rankMeta=metaService.queryMetaInfo(storeRankId);
		int rs=0;
		List<Attr> attrList=attrDAO.findByFidAndRank(id, storeRankId);
		Map<String,Attr> attrMap=MapUtil.groupListBeanBy(attrList, "name", String.class);
		Map<String,MField> fm=meta.getNameFieldMap();
		for(Map.Entry<String, String> e:attrs.entrySet()) {
			MField f=fm.get(e.getKey());
			if(f!=null) {
				Attr a=attrMap.get(e.getKey());
				if(a!=null) {
					if(!StringUtils.equals(a.getCode(), e.getValue())) {
						a.setCode(e.getValue());
						a.setMeta(metaId);
						attrDAO.save(a);
						rs+=1;
					}
				}else {
					a=new Attr();
					a.setFid(id);
					a.setName(f.getName());
					a.setCode(e.getValue());
					a.setText("");
					a.setFlag(1);
					a.setRank(storeRankId);
					a.setMeta(metaId);
					attrDAO.save(a);
					rs+=1;
				}
			}
			
		}
		return rs;
	}

}
